<template>
  <div>
    <div class="flex margin-bottom-20">
      <div>
        <span class="label-txt">所属财年</span>
      </div>
      <div class="input-box">
        <span>{{ $route.query.year }}</span>
        <span v-if="$route.query.month && pageType != 'year'">-{{ $route.query.month }}</span>
      </div>
      <div>
        <span class="label-txt margin-right-40 t-center">所属项目</span>
        <span>{{ projectName }}</span>
      </div>
    </div>

    <div v-if="pageType == 'year' || pageType == 'month'" class="flex align-center">
      <div class="padding-right-40 label-txt">项目{{ pageTypeTxt }}{{ pageType == 'month' ? '执行' : '' }}计划</div>
      <div class="input-box">
        <el-input size="mini" v-model="planFile.name" :readonly="true" @focus="downFile('planFile')"></el-input>
      </div>
      <uploadFile v-if="procStatus != 1 && procStatus != 2" class="margin-right-40 label-txt t-center" buttonType="text" isShowList="" btnName="上传附件" filed-name="file" :max-size="70" accept-file-type=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.docx,.pdf,.zip" @handleSuccess="handleSuccess($event, 'planFile')" @beforeUpload="beforeUpload($event, 'planFile')"></uploadFile>
      <el-button v-if="procStatus != 1 && procStatus != 2" type="text" @click="downPlanTemplate">下载模板</el-button>
    </div>

    <div class="flex align-center margin-top-15">
      <div class="padding-right-40 label-txt">{{ pageTypeTxt }}利润底表</div>
      <div class="input-box">
        <el-input size="mini" v-model="profitFile.name" :readonly="true" @focus="downFile('profitFile')"></el-input>
      </div>
      <uploadFile v-if="procStatus != 1 && procStatus != 2" class="margin-right-40 label-txt t-center" buttonType="text" isShowList="" btnName="上传附件" filed-name="file" :max-size="70" accept-file-type=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.docx,.pdf,.zip" @handleSuccess="handleSuccess($event, 'profitFile')"></uploadFile>
    </div>

    <div class="flex align-center margin-top-15">
      <div class="padding-right-40 label-txt">{{ pageTypeTxt }}现金流底表</div>
      <div class="input-box">
        <el-input size="mini" v-model="cashFile.name" :readonly="true" @focus="downFile('cashFile')"></el-input>
      </div>
      <uploadFile v-if="procStatus != 1 && procStatus != 2" class="margin-right-40 label-txt t-center" buttonType="text" isShowList="" btnName="上传附件" filed-name="file" :max-size="70" accept-file-type=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.docx,.pdf,.zip" @handleSuccess="handleSuccess($event, 'cashFile')"></uploadFile>
    </div>

    <div class="margin-top-40" v-if="btnShow">
      <el-button class="f-right" type="primary" size="mini" @click="submit">提 交</el-button>
      <el-button class="f-right margin-right-10" type="primary" size="mini" @click="save">保 存</el-button>
    </div>

    <!-- <approve-info v-if="procStatus" class="padding-top-30" :workId="$route.query.taskId"></approve-info> -->

    <!-- 展示上传失败的和其原因 -->
    <el-dialog title="上传结果" :visible.sync="dialogShow" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="margin-bottom-20" v-if="pageType == 'year' || pageType == 'month'">
        <span class="padding-right-40 label-txt">项目{{ pageTypeTxt }}{{ pageType == 'month' ? '执行' : '' }}计划</span>
        <span :class="planFile.res.success == false ? 'color-red' : ''">{{ planFile.res.message || '上传成功' }}</span>
      </div>
      <div class="margin-bottom-20">
        <span class="padding-right-40 label-txt">{{ pageTypeTxt }}利润底表</span>
        <span :class="!profitFile.res.success ? 'color-red' : ''">{{ profitFile.res.message }}</span>
      </div>
      <div>
        <span class="padding-right-40 label-txt">{{ pageTypeTxt }}现金流底表</span>
        <span :class="!cashFile.res.success ? 'color-red' : ''">{{ cashFile.res.message }}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogShow = false">返回重新上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { projectList } from '@/api';
  import Api from '../../../../api/incomeAndExpenditurePlan';
  import uploadFile from '@/common/components/upload.vue';
  import { requestTips, askDialog } from '@/common/js/utils.js';
  import approveInfo from '@/common/components/approveInfo';
  import { detailByTaskId } from '@/api';

  export default {
    name: 'plan-upload-content',

    props: {
      // year 年度,  month 月度执行计划,  monthDone 月度执行
      pageType: {
        type: String,
        default: '',
      },
    },

    computed: {
      pageTypeTxt() {
        return this.pageType == 'year' ? '年度' : '月度';
      },
      btnShow() {
        if (this.pageType == 'monthDone') {
          return this.flowInfo.state == 'approve' ? false : true;
        } else {
          return this.procStatus != 1 && this.procStatus != 2 ? true : false;
        }
      },
    },

    data() {
      return {
        procStatus: '',
        projectName: '',
        planFileChange: false, // 计划的文件是否发生变化
        planFile: {
          name: '',
          fileUrl: '',
          file: null,
          res: {},
        },
        profitFile: {
          name: '',
          fileUrl: '',
          file: null,
          res: {},
        },
        cashFile: {
          name: '',
          fileUrl: '',
          file: null,
          res: {},
        },
        fileList: [],
        dialogShow: false,
        flowInfo: { state: 'approve' },
      };
    },

    mounted() {
      this.getProjectList();
      this.getInfo();
      this.pageType == 'monthDone' && this.getDetailByTaskId();
    },

    methods: {
      //项目列表
      async getProjectList() {
        const res = await projectList({});
        const target = res.rows.find(item => item.projectKey == this.$route.query.projectKey);
        this.projectName = target ? target.projectName : '';
      },

      //详情
      async getInfo() {
        const res = await Api.batchFileInfo({ targetKey: this.$route.query.taskId, status: 1, planKey: this.$route.query.planKey });
        this.procStatus = res.procStatus;
        res.rows.forEach(item => {
          this[item.targetType + 'File'].name = item.attachmentName;
          this[item.targetType + 'File'].fileUrl = item.attachmentUrl;
        });
      },

      //流程信息
      async getDetailByTaskId() {
        let res = await detailByTaskId({ taskId: this.$route.query.taskId });
        this.flowInfo = res;
      },

      //下载模板
      async downPlanTemplate() {
        this.showLoading();
        await Api.apiExportPlan({ planKey: this.$route.query.planKey }).then(res => {});
        this.loading.close();
      },

      //上传前,用于储存计划的file文件流
      beforeUpload(data, objName) {
        if (objName == 'planFile') {
          this.planFile.file = data;
        }
      },

      //上传成功
      handleSuccess(data, objName) {
        if (objName == 'planFile') {
          this.planFileChange = true;
        }
        this[objName].name = data.file.name || '';
        this[objName].fileUrl = data.result.data.rows[0].url || '';
      },

      //上传项目年度计划方法
      async importPlanFile(file) {
        return new Promise(async (resolve, reject) => {
          this.showLoading();
          Api.apiImportPlan(file)
            .then(res => {
              this.planFile.res = res;
              this.loading.close();
              resolve(res);
            })
            .catch(err => {
              this.planFile.res = err.data;
              this.loading.close();
              reject(err);
            });
        });
      },

      //上传年度利润表 年度现金流底表 方法
      async importOtherFile(fileUrl, type) {
        if (!fileUrl) return;
        let params = {
          projectKey: this.$route.query.projectKey,
          subjectType: type == 'profit' ? 1 : 2,
          fileUrl: fileUrl,
        };
        if (this.pageType == 'year') {
          params.importType = 1;
          params.date = this.$route.query.year;
        } else if (this.pageType == 'month') {
          params.importType = 2;
          params.date = this.$route.query.year + '-' + this.$route.query.month;
        } else if (this.pageType == 'monthDone') {
          params.importType = 3;
          params.date = this.$route.query.year + '-' + this.$route.query.month;
        }
        return new Promise(async (resolve, reject) => {
          Api.apiExportOtherPlan(params)
            .then(res => {
              if (type == 'profit') {
                this.profitFile.res = res;
              } else {
                this.cashFile.res = res;
              }
              resolve(res);
            })
            .catch(err => {
              if (type == 'profit') {
                this.profitFile.res = err.data;
              } else {
                this.cashFile.res = err.data;
              }
              reject(err);
            });
        });
      },

      //保存
      async save(type) {
        let lock = true;
        let requestArr = [this.importOtherFile(this.profitFile.fileUrl, 'profit'), this.importOtherFile(this.cashFile.fileUrl, 'cash')];
        if (this.pageType == 'monthDone') {
          if (!this.profitFile.fileUrl || !this.cashFile.fileUrl) {
            this.$message.warning('请上传！');
            return;
          }
        } else {
          if (!this.planFile.fileUrl) {  //|| !this.profitFile.fileUrl || !this.cashFile.fileUrl
            this.$message.warning('请上传！');
            return;
          }
          if (this.planFileChange) {
            requestArr.unshift(this.importPlanFile(this.planFile.file));
          }
        }

        await Promise.all(requestArr).catch(err => {
          lock = false;
        });

        if (!lock) {
          this.dialogShow = true;
          return;
        }
        let params = {
          businessKey: this.$route.query.taskId,
          list: [],
        };
        if (this.pageType == 'year' || this.pageType == 'month') {
          params.list.push({
            targetType: 'plan',
            attachmentName: this.planFile.name,
            attachmentUrl: this.planFile.fileUrl,
          });
        }
        if (this.profitFile.fileUrl) {
          params.list.push({
            targetType: 'profit',
            attachmentName: this.profitFile.name,
            attachmentUrl: this.profitFile.fileUrl,
          });
        }
        if (this.cashFile.fileUrl) {
          params.list.push({
            targetType: 'cash',
            attachmentName: this.cashFile.name,
            attachmentUrl: this.cashFile.fileUrl,
          });
        }
        let res = await Api.batchFileSave(params);
        if (res.success) {
          if (type == 'submit') {
            this.submitFn();
          } else {
            this.$message.success(res.message);
            this.getInfo();
          }
        } else {
          this.$message.error(res.message);
        }
      },

      //提交
      submit() {
        askDialog('确认提交？', async () => {
          this.save('submit');
        });
      },

      //提交方法
      async submitFn() {
        let res = {};
        if (this.pageType == 'monthDone') {
          res = await Api.batchFileMonthDoneSubmit({ taskid: this.$route.query.taskId });
        } else {
          res = await Api.submitTableCopy({ primaryKey: this.$route.query.planKey });
        }
        requestTips(res, () => {
          if (res.success) {
            this.$message.success(res.message);
            this.getInfo();
            if (this.pageType == 'monthDone') this.getDetailByTaskId();
          } else {
            this.$message.warning(res.message);
          }
          this.loading && this.loading.close();
        });
      },

      //下载文件
      downFile(type) {
        if (!this[type].fileUrl) return;
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = this[type].fileUrl;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      },

      showTips(message) {
        if (message == '导入成功') {
          this.$message.success(message);
        } else {
          this.$message.warning(message);
        }
      },

      showLoading() {
        this.loading = this.$loading({
          lock: true,
          text: '加载中……',
          background: 'rgba(0, 0, 0, 0.7)',
        });
      },
    },

    components: { uploadFile, approveInfo },
  };
</script>

<style lang="scss" scoped>
  div,
  span {
    font-size: 16px;
  }
  .input-box {
    width: 300px;
  }
  ::v-deep .el-button span {
    font-size: 16px;
  }
  .label-txt {
    width: 180px;
    display: inline-block;
  }
</style>
